<template>
  <view class="coupon-container">
    <!-- 头部 -->
    <view class="header">
      <view class="title">我的优惠券</view>
    </view>
    
    <!-- 优惠券列表 -->
    <view class="coupon-list" v-if="coupons.length > 0">
      <view 
        class="coupon-item"
        v-for="(coupon, index) in coupons" 
        :key="index"
      >
        <view class="coupon-left">
          <view class="amount">
            <text v-if="coupon.type === 'amount'" class="symbol">¥</text>
            <text class="value">{{ formatAmount(coupon) }}</text>
            <text v-if="coupon.type === 'percentage'" class="symbol">%</text>
          </view>
          <view class="min-amount" v-if="coupon.minAmount > 0">满{{ coupon.minAmount }}元可用</view>
        </view>
        
        <view class="coupon-right">
          <view class="coupon-name">{{ coupon.name }}</view>
          <view class="coupon-desc">{{ coupon.description || '全场通用' }}</view>
          <view class="coupon-time">
            {{ formatDate(coupon.startTime) }} - {{ formatDate(coupon.endTime) }}
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else>
      <image class="empty-image" src="/static/images/empty.png" mode="aspectFit"></image>
      <text class="empty-text">暂无可用优惠券</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { couponApi } from '@/api/index.js';
import common from '@/utils/common.js';

// 响应式数据
const coupons = ref([]);

// 生命周期钩子
onMounted(() => {
  loadCoupons();
});

// 加载优惠券列表
const loadCoupons = async () => {
  try {
    uni.showLoading({ title: '加载中...' });
    const res = await couponApi.getUserCoupons();
    if (res.code === 200) {
      coupons.value = res.data || [];
    } else {
      common.showToast(res.msg || '获取优惠券失败');
    }
  } catch (error) {
    console.error('获取优惠券失败:', error);
    common.showToast('获取优惠券失败，请检查网络');
  } finally {
    uni.hideLoading();
  }
};

// 格式化优惠券金额
const formatAmount = (coupon) => {
  if (coupon.type === 'amount') {
    return formatNumber(coupon.amount);
  } else if (coupon.type === 'percentage') {
    return formatNumber(coupon.amount * 100);
  }
  return '0';
};

// 格式化数字，保留两位小数并去除末尾的0
const formatNumber = (num) => {
  if (typeof num !== 'number') return '0';
  return Number(num.toFixed(2)).toString();
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  
  // 为了兼容iOS，将日期字符串转换为标准格式
  try {
    // 解析日期字符串
    const parts = dateStr.split(/[- :T]/);
    if (parts.length >= 3) {
      // 使用 yyyy/MM/dd 格式创建日期，这种格式iOS兼容性更好
      const year = parts[0];
      const month = parts[1].padStart(2, '0');
      const day = parts[2].padStart(2, '0');
      
      // 使用标准格式创建日期
      const date = new Date(`${year}/${month}/${day}`);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn('无效的日期:', dateStr);
        return dateStr.substring(0, 10); // 至少返回原始日期的一部分
      }
      
      return `${date.getFullYear()}.${date.getMonth() + 1}.${date.getDate()}`;
    }
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateStr.substring(0, 10); // 在错误情况下返回原始日期的一部分
  }
  
  return dateStr.substring(0, 10);
};
</script>

<style scoped>
.coupon-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.coupon-list {
  margin-top: 20rpx;
}

.coupon-item {
  display: flex;
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.coupon-left {
  width: 220rpx;
  background: linear-gradient(135deg, #ff6700 0%, #ff9500 100%);
  padding: 30rpx 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #fff;
  position: relative;
}

.coupon-left::after {
  content: '';
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  width: 20rpx;
  background-image: linear-gradient(90deg, transparent 0%, transparent 50%, #fff 50%, #fff 100%);
  background-size: 20rpx 20rpx;
  transform: translateX(10rpx);
}

.amount {
  display: flex;
  align-items: baseline;
}

.symbol {
  font-size: 36rpx;
  font-weight: bold;
}

.value {
  font-size: 64rpx;
  font-weight: bold;
}

.min-amount {
  font-size: 24rpx;
  margin-top: 10rpx;
  opacity: 0.8;
}

.coupon-right {
  flex: 1;
  padding: 30rpx;
}

.coupon-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.coupon-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.coupon-time {
  font-size: 24rpx;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}
</style> 